package com.dongdongqiang.admin.controller;

import com.dongdongqiang.admin.enums.CacheName;
import com.dongdongqiang.admin.service.SysPermissionService;
import com.dongdongqiang.admin.service.SysRoleService;
import com.dongdongqiang.common.base.BaseTreeVO;
import com.dongdongqiang.domain.sys.SysPermission;
import com.dongdongqiang.domain.sys.SysRole;
import com.dongdongqiang.domain.sys.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZZB on 2017/9/24.
 */
@Controller
public class LoginController extends SysUserLoginController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(HttpServletRequest request){
        return "/login";
    }

    @RequestMapping("/loginUser")
    public String loginUser(String username,String password,HttpServletRequest request) {
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            SysUser user=(SysUser) subject.getPrincipal();
            saveUserSession(request,user);
            return "redirect:/sys/main";
        } catch(Exception e) {
            return "login";//返回登录页面
        }
    }

    @RequestMapping("/logOut")
    public String logOut(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        removeUserSession(request);
        return "redirect:/login";
    }

    @Override
    public void saveUserSession(HttpServletRequest request, SysUser sysUser) {
        putPermissionInSession(sysUser.getId(),request.getSession());
        super.saveUserSession(request, sysUser);
    }

    @Override
    public void removeUserSession(HttpServletRequest request) {
        request.getSession().removeAttribute(CacheName.SYS_PERMISSTION_MAP.name());
        request.getSession().removeAttribute(CacheName.SYS_PERMISSTION_TREE_VO.name());
        super.removeUserSession(request);
    }

    private void putPermissionInSession(String userId, HttpSession session){
        Map<String ,SysPermission> permissionMap = new HashMap<>();
        List<SysRole> roles = sysRoleService.queryByUserId(userId);
        if(roles.size()>0) {
            for(SysRole role : roles) {
                List<SysPermission> sysPermissions = sysPermissionService.queryByRoleId(role.getId());
                if(sysPermissions.size()>0) {
                    for( SysPermission sysPermission : sysPermissions) {
                        permissionMap.put(sysPermission.getId(),sysPermission);
                    }
                }
            }
        }

        //构建权限树并放入到缓存中
        BaseTreeVO<SysPermission> treeVO = sysPermissionService.buildTreeVOByMap(permissionMap);
        session.setAttribute(CacheName.SYS_PERMISSTION_MAP.name(),permissionMap);
        session.setAttribute(CacheName.SYS_PERMISSTION_TREE_VO.name(),treeVO);
    }

}
